package com.digua.frame.plugin.utils;

import com.lionbridge.skywalking.extension.config.Constants;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.Config.Agent;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.os.OSUtil;
import org.apache.skywalking.apm.util.StringUtil;

import java.util.List;

/**
 * @description:
 * @author: wangzhilong
 * @date: 2021/10/20
 **/
public class TraceUtils {
    public static String getHost() {
        String host = "host:N/A";
        if (Constants.HOST.equals(host)) {
            List<String> ips = OSUtil.getAllIPV4();
            if (null != ips && ips.size() > 0) {
                host = (String)ips.get(0);
            }
        } else {
            host = Constants.HOST;
        }

        return host;
    }

    public static String getTraceId(TraceSegment segment) {

        String traceId = "traceId:N/A";
        if (null != segment) {
            traceId = segment.getTraceSegmentId();
        }

        return traceId;
    }

    public static String getServiceName() {
        String serviceName = "serviceName:N/A";
        if (StringUtil.isNotEmpty(Agent.SERVICE_NAME)) {
            serviceName = Agent.SERVICE_NAME;
        }

        return serviceName;
    }

    public static String getServiceInstanceName() {
        String serviceInstanceName = "serviceInstanceName:N/A";
        if (StringUtil.isNotEmpty(Agent.INSTANCE_NAME)) {
            serviceInstanceName = Agent.INSTANCE_NAME;
        }

        return serviceInstanceName;
    }

    public static String genServiceInstanceName() {
        String appKey = "serviceInstanceName:N/A";
        if (!StringUtil.isEmpty(Agent.INSTANCE_NAME)) {
            appKey = Agent.INSTANCE_NAME;
        }

        return appKey;
    }

    public static int fnvHash(String data) {
        int p = 16777619;
        int hash = -2128831035;

        for(int i = 0; i < data.length(); ++i) {
            hash = (hash ^ data.charAt(i)) * 16777619;
        }

        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;
        return Math.abs(hash);
    }

    public static void main(String[] args) {
        System.out.println(fnvHash("127.0.0.1"));
    }

}
